package com.ygqh.baby.observer;

import com.foxinmy.weixin4j.tuple.Text;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.service.WxMpMessageService;
import com.ygqh.baby.service.YgDrawPrizeHelpService;
import com.ygqh.baby.service.YgUserOpenService;
import com.ygqh.baby.utils.WebUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 抽奖助力
 *
 * @author: sunshuo
 * @date: 2018/12/25 16:00
 */
@Component
public class DrawPrizeHelpObserver implements Observer {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	private final ExecutorService executorService = Executors.newFixedThreadPool(3);

	@Autowired
	private YgDrawPrizeHelpService ygDrawPrizeHelpService;
	@Autowired
	private YgUserOpenService ygUserOpenService;
	@Autowired
	private WxMpMessageService wxMpMessageService;

	@Override
	public void update(Observable o, Object arg) {
		ChannelScanModel model = arg != null ? (ChannelScanModel) arg : null;
		if (model == null) {
			logger.error("【DrawPrizeHelpObserver】参数异常");
			return;
		}
		if (StringUtils.isBlank(model.getSeoId()) || !model.getSeoId().startsWith("DrawPrize-")) {
			logger.info("【DrawPrizeHelpObserver】非助力sourceCode，seoid={}", model.getSeoId());
			return;
		}
		if (!model.isSubscribe()) {
			logger.info("【DrawPrizeHelpObserver】非关注公众号事件，seoid={}，openid={}", model.getSeoId(), model.getOpenId());
			return;
		}
		Boolean exist = ygUserOpenService.existBySubscribe(model.getOpenId());
		if (exist) {
			logger.info("【DrawPrizeHelpObserver】非第一次关注公众号，seoid={}，openid={}", model.getSeoId(), model.getOpenId());
			return;
		}
		Message message = ygDrawPrizeHelpService.addWxHelp(model.getSeoId(), model.getOpenId());
		if (message.getType().equals(Message.Type.success)) {
			model.setContent(message.getContent());
		} else {
			logger.warn("【DrawPrizeHelpObserver】" + message.getContent());
		}
		triggerOtherEvent(model.getOpenId());
	}

	private void triggerOtherEvent(String openId) {
		executorService.execute(() -> {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			logger.info("【DrawPrizeHelpObserver】助力事件结束，开始发送图文消息");

//			String url = WebUtils.generateShortUrl("http://m.yiigoo.com/static/1567395583.html?sourceCode=190901");
			String content = "壹果YIIGOO三岁啦！\n" +
					"店庆限定新品每周首发，帐篷拉杆箱购物免费拿，更有羊毛大转盘抢920元现金、大额优惠券和马卡龙腕包等，周年party即刻开启：";
			wxMpMessageService.sendCustomMsg(new Text(content), openId, null);
		});
	}

}
